#include <8052.h>
#include "Delay.h"

/**
  * @brief  矩阵键盘读取按键键码
  * @param  无
  * @retval key_number 按下按键的键码值
			如果按键按下不放，程序会停留在此函数，松手的一瞬间返回按键键码，没有按键按下时返回0
  */

unsigned char MatrixKey() {
	unsigned char key_number = 0;
	// 按列扫描
	P1 = 0xFF;  // 全部置高电位 11111111
	P1_3 = 0;  // 第1列置0
	if (P1_7 == 0) {
		Delay(20);  // 消抖
		while (P1_7 == 0) {}  // 检测松手
		Delay(20);
		key_number = 1;
	}
	if (P1_6 == 0) {
		Delay(20);
		while (P1_6 == 0) {}
		Delay(20);
		key_number = 5;
	}
	if (P1_5 == 0) {
		Delay(20);
		while (P1_5 == 0) {}
		Delay(20);
		key_number = 9;
	}
	if (P1_4 == 0) {
		Delay(20);
		while (P1_4 == 0) {}
		Delay(20);
		key_number = 13;
	}
	
	P1 = 0xFF;
	P1_2 = 0;  // 第2列置0
	if (P1_7 == 0) {
		Delay(20);
		while (P1_7 == 0) {}
		Delay(20);
		key_number = 2;
	}
	if (P1_6 == 0) {
		Delay(20);
		while (P1_6 == 0) {}
		Delay(20);
		key_number = 6;
	}
	if (P1_5 == 0) {
		Delay(20);
		while (P1_5 == 0) {}
		Delay(20);
		key_number = 10;
	}
	if (P1_4 == 0) {
		Delay(20);
		while (P1_4 == 0) {}
		Delay(20);
		key_number = 14;
	}
	
	P1 = 0xFF;
	P1_1 = 0;  // 第3列置0
	if (P1_7 == 0) {
		Delay(20);
		while (P1_7 == 0) {}
		Delay(20);
		key_number = 3;
	}
	if (P1_6 == 0) {
		Delay(20);
		while (P1_6 == 0) {}
		Delay(20);
		key_number = 7;
	}
	if (P1_5 == 0) {
		Delay(20);
		while (P1_5 == 0) {}
		Delay(20);
		key_number = 11;
	}
	if (P1_4 == 0) {
		Delay(20);
		while (P1_4 == 0) {}
		Delay(20);
		key_number = 15;
	}
	
	P1 = 0xFF;
	P1_0 = 0;  // 第4列置0
	if (P1_7 == 0) {
		Delay(20);
		while (P1_7 == 0) {}
		Delay(20);
		key_number = 4;
	}
	if (P1_6 == 0) {
		Delay(20);
		while (P1_6 == 0) {}
		Delay(20);
		key_number = 8;
	}
	if (P1_5 == 0) {
		Delay(20);
		while (P1_5 == 0) {}
		Delay(20);
		key_number = 12;
	}
	if (P1_4 == 0) {
		Delay(20);
		while (P1_4 == 0) {}
		Delay(20);
		key_number = 16;
	}
	
	return key_number;
}
